const { exec } = require("child_process");
const xSpinner = require("./utils/ora")();
export default function Build() {
  const virtualFileId = "@rollup-plugin-build";

  return {
    name: "my-plugin", // 必须的，将会显示在 warning 和 error 中
    resolveId(id) {
      if (id === virtualFileId) {
        return virtualFileId;
      }
    },
    load(id) {
      if (id === virtualFileId) {
        return `export const msg = "from virtual file"`;
      }
    },
    buildStart(options) {},
    async closeBundle(err) {
      console.log(" \n -------- Build Finished! --------");
      console.log(" \n -------- Start copy Vercel deploy files --------");
      await exec("cp -r .vercel ./dist");
      await exec("cp now.json ./dist");

      console.log(" \n -------- Start deploy on Vercel --------");
      xSpinner.start();
      exec("vercel dist --prod", async function (error, stdout, stderr) {
        xSpinner.stop();

        stdout && console.log(stdout);
        stderr && console.log(stderr);
        if (error) {
          console.error("[vercel 部署失败]", error);
        } else {
          console.log("[海报生成器] Vercel部署完成✌️");
        }

        let cmd = `git pull && git add . && git commit -m "feat: 更新" && git push`;
        exec(cmd, function (error, stdout, stderr) {
          console.log(`- 仓库提交结果如下： \n\n${stdout}`);
        });
      });
    },
  };
}
